	#include <stdio.h>
	#include <stdlib.h>
	#include <sys/types.h>
	#include <sys/stat.h>
	#include <unistd.h>
	#include <time.h>
	#include <string.h>

	FILE * fl;
	int sizelogfile;
	#define sizebuf 10240 
	int sizebufzapoln;
	char buf[sizebuf];
	char * progname;


int renamefile()
{
	// find the correct name for renaming Log file
	int i=1;
	int ren;
	char *str;
	do
	{
		i++;
		sprintf(str, "log%d.txt", i);
	} while(access(str, F_OK) == 0 );

	// rename Log file
	ren = rename("log.txt", str);
	sizelogfile = 0;
	return ren;
}


int prov_buf(int length)
{
	int numbpr;
	// check if there is enough place in the buffer
	if ((length + sizebufzapoln)>=sizebuf)
	{
		// buf -> file
		if (numbpr = fprintf(fl, "%s", buf) < 0)
		{
			perror("Error printing to Log file");
			return -1;
		}
		sizelogfile = sizelogfile + numbpr;
		sizebufzapoln = 0;

		// chek file length
		if (sizelogfile > 10485760)
		{
			if (fclose(fl) != 0)
			{
				perror("Error closing Log file");
				return -1;
			}
			// rename and create new Log file
			if (renamefile() != 0)
			{
				perror("Error renaming Log file");
				return -1;
			}
			fl = fopen("log.txt", "a+");
			if (fl==NULL)
			{
				perror("Error opening Log file");
				return -1;
			}
		}
	}
	return 0;
}


int logstart (char * name)
{
	struct stat sb;

	progname = name;

	// check whether the log.txt exists

	if (access("log.txt", F_OK) == 0 )
	{
		// check log file length
		if (stat("log.txt", &sb) == -1) {
			perror("Cannot get information about Log file");
			return -1;
		}
		sizelogfile = sb.st_size;
		// rename log file if if is too long
		if (sizelogfile > 10485760)
		{
			if (renamefile() != 0)
			{
				perror("Error renaming Log file");
				return -1;
			}
		}
	}
	// open or create log file
	fl = fopen("log.txt", "a+");
	if (fl==NULL)
	{
		perror("Error opening Log file");
		return -1;
	}
	return 0;
}


int logm (char * loglevel, char * message)
{
	int numbb;
	int length;
	time_t timeptr;
	struct tm * timeinfo;
	char * timeasc;

	time(&timeptr);
	timeinfo = localtime(&timeptr);
	timeasc = asctime(timeinfo);
	// length = the length of the message
	length = strlen(loglevel) + strlen(timeasc) + strlen(message) + strlen(progname)+11;

	// check if there is enough place in the buffer, if not writes it to log file and then check log file
	if (prov_buf(length) == -1)
	{
		return -1;
	}

	if ((numbb = sprintf(buf+sizebufzapoln, "%s     - %s, %s, %s\n", timeasc, loglevel,  progname, message)) < 0)
	{
		perror("Error writing to Log buf");
		return -1;
	}
	sizebufzapoln = sizebufzapoln + numbb;
	return 0;
}


int logend ()
{
	int i=0;
	int numbpr;
	// buf -> file
	if (numbpr = fprintf(fl, "%s", buf) < 0)
	{
		perror("Error printing to Log file");
		i=-1;
	}
	if (fclose(fl) != 0)
	{
		perror("Error closing Log file");
		i= -1;
	}
	return i;
}
